<?php
session_start();
if (!defined('ROOT')) {
    $root = $_SERVER['DOCUMENT_ROOT'];
    define('ROOT', $_SERVER['DOCUMENT_ROOT'].'/../');
}
header('Content-type: text/json');
// require_once($root.'/../vendor/autoload.php');

class Env
{
    public $datas = [];
    public function __construct()
    {
        $file = ROOT.'/.env';
        if (file_exists($file) && is_file($file)) {
            $handle = @fopen($file, 'r');
            if ($handle) {
                while (($buffer = fgets($handle)) !== false) {
                    $content = trim($buffer);
                    if (empty($content)) {
                        continue;
                    }
                    if (strpos($content, '#')===0 || strpos($content, '//')===0) {
                        continue;
                    }
                    $kv = explode('=', $content, 2);
                    $key = trim(@$kv[0]);
                    $value = trim(@$kv[1]);
                    $this->datas[$key] = $value;
                }
                if (!feof($handle)) {}
                fclose($handle);
            }
        }
    }

    public function get($key=null)
    {
        if (empty($key)) {
            return null;
        }
        return @$this->datas[$key];
    }
}


class Pdodb
{
    public $pdo;

    public function __construct()
    {
        $env = new Env();
        $host = $env->get('DB_HOST');
        $dbname = $env->get('DB_DATABASE');
        $user = $env->get('DB_USERNAME');
        $pwd = $env->get('DB_PASSWORD');
        $dsn='mysql:host='.$host.';dbname='.$dbname;
        try {
            $this->pdo= new PDO($dsn,$user,$pwd);
            $this->pdo->query("set names utf8mb4");
            // $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            // $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        }catch(Exception $e){
            exit ();
        }

    }

    public function query($sql)
    {
        try {
            $sj = $this->pdo->prepare($sql);
            $sj->execute();
            $jg = $sj->fetchall(PDO::FETCH_ASSOC);
            return $jg;
        } catch(Exception $e){
            fs500('服务器错误');
            exit ();
        }
    }

    public function find($id)
    {

    }
}

class httpStatus
{
    protected $headerStatus = [
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out"
    ];
    public function __construct($status, $msg, $data=[], ...$arg)
    {
        $header = $this->status($status);
        if (in_array($status, [200])) {
            $res = $this->success($msg, $data, $arg);
        } else {
            $res = $this->fail($msg, $data, $arg);
        }
        echo json_encode($res);
    }

    protected function status($status)
    {
        $header = @$this->headerStatus[$status];
        if (empty($header)) {
            $header = @$this->headerStatus(404);
        }
        $state = str_replace('HTTP/1.1', 'status:', $header);
        header($state);
        header($state);
    }

    public function fail($msg, $data=[], ...$arg)
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'Fail';
        }
        $res = [
            'status' => false,
            'msg' => $msg,
            'data' => $data,
            $arg,
        ];
        return $res;
    }

    public function success($msg, $data=[], ...$arg)
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'SUCCESS';
        }
        $res = [
            'status' => 'SUCCESS',
            'msg' => $msg,
            'data' => $data,
            $arg,
        ];
        return $res;
    }
}
function fs403($msg, $data=[], ...$arg) {
    new httpStatus(403, $msg, $data, $arg);
}
function fs404($msg, $data=[], ...$arg) {
    new httpStatus(404, $msg, $data, $arg);
}
function fs200($msg, $data=[], ...$arg) {
    new httpStatus(200, $msg, $data, $arg);
}
function fs200d($msg, $data=[], ...$arg) {
    new httpStatus(200, $msg, $data, $arg);
}
function fs500($msg, $data=[], ...$arg) {
    new httpStatus(500, $msg, $data, $arg);
}

function request($key=null) {
    $request = array_merge($_GET, $_POST);
    if ($key === null || $key==='') {
        return @$request;
    }
    return @$request[$key];
}

/*
 * 获取卷号长度
 * 根据用户ID获取剩余卷号*/
class myAjax
{

    public function __construct()
    {
        $t = request('t');
        if (in_array($t, ['roll', 'search', 'test1'])) {
            return $this->$t();
        }
        $a = request('a');
        return fs404('没有找到');

    }

    public function test1()
    {
        $sql = 'select * from users limit 50';
        $res = $this->db()->query($sql);
        return fs200($res);
        // echo  json_encode($res);
    }

    public function search()
    {
        $user_id = request('user_id');
        if (empty($user_id)) {
            return fs403('用户不能为空！');
        }
        $q = request('q');
        if (empty($q)) {
            return fs403('参数不完整！');
        }
        $sql = 'select rm.id, rm.roll_number,ftm.product_type_id from roll_master as rm left join roll_restlen as rr on rm.roll_number=rr.roll_number left join film_type_master as ftm on rm.film_type_id=ftm.id where rm.roll_number like "'.$q.'%" and rr.user_id="'.$user_id.'" and rr.restlen>0 and rm.deleted_at is null and rr.deleted_at is null order by rm.id desc limit 8';

        $res = $this->db()->query($sql);
        return fs200($res);
    }

    public function roll()
    {

    }

    protected function db()
    {
        return new Pdodb();
    }

}


$ajax = new myAjax();
?>